# -*- coding: UTF-8 -*-
#
import os
import sys
import time
import getopt
import shutil
import exifread
import re
import json
import requests
from datetime import datetime
from pathlib import Path
import traceback


kImageDateFmt = '%Y:%m:%d'

gLocToAddr = {'123.957106,47.339553': {'province': '黑龙江省', 'city':'齐齐哈尔市', 'district':'龙沙区'}}
# gLocToAddr = {'123.957106,47.339553': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '龙沙区'}, '123.957097,47.339506': {'province': '黑龙江省', 'city': '齐齐 哈尔市', 'district': '龙沙区'}, '123.957144,47.339636': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '龙沙区'}, '123.957153,47.339311': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '龙沙区'}, '123.957158,47.339453': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '龙沙区'}, '123.957158,47.339472': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '龙沙区'}, '123.957169,47.339650': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '龙沙区'}, '123.951772,47.328819': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '龙沙区'}, '124.212119,47.195914': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.210848,47.195558': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.233219,47.194178': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.233153,47.194272': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.232794,47.195097': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.234436,47.197336': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.234825,47.198408': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.237839,47.204472': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.237447,47.201208': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.236719,47.200275': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.236928,47.199444': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.235550,47.196944': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.235175,47.196847': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}, '124.198185,47.221081': {'province': '黑龙江省', 'city': '齐齐哈尔市', 'district': '铁锋区'}}
def is_video_file(filename):
    video_extensions = {'mp4', 'avi', 'mkv', 'mov', 'wmv', 'mpg', 'mpeg'}
    return os.path.splitext(filename)[1].lower()[1:] in video_extensions


def is_photo(file_path):
    extensions = {'jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'heic'}
    return os.path.splitext(file_path)[1].lower()[1:] in extensions


def is_image_file(filename):
    video_extensions = {'mp4', 'avi', 'mkv', 'mov', 'wmv', 'mpg', 'mpeg'}
    return filename.lower().endswith(video_extensions)


def get_address_by_gaode(location):
        parameters = {'location': location, 'key': 'ae30ded5e9664a6ae45c9b58915dc84b'}
        base = 'http://restapi.amap.com/v3/geocode/regeo'
        response = requests.get(base, parameters)
        if response.status_code != 200:
            print(response)
            return None

        answer = response.json()
        if answer['status'] != '1':
            print(answer)
            return None

        # answer['regeocode']['formatted_address']
        province = answer['regeocode']['addressComponent']['province']
        city = answer['regeocode']['addressComponent']['city']
        district = answer['regeocode']['addressComponent']['district']
        return {'province': province,
                            'city':city,
                             'district':district}


# 转换经纬度格式
def latitude_and_longitude_convert_to_decimal_system(deg, min, sec):
    """
    经纬度转为小数
    :param deg: 度
    :param min: 分
    :param sec: 秒（可以是分数形式，如"30/1"）
    :return: 十进制小数
    """
    try:
        sec = float(sec.split('/')[0]) / float(sec.split('/')[1]) if '/' in sec else float(sec)
        return float(deg) + (float(min) / 60.0) + (sec / 3600.0)
    except:
        return None


# 输出经纬度（度、分、秒）
def Position(x, y):
    nsl = x
    ewl = y

    '''度'''
    angle1 = int(nsl)
    angle2 = int(ewl)

    '''分'''
    min1 = int((nsl - angle1) * 60)
    min2 = int((ewl - angle2) * 60)

    '''秒'''
    second1 = round((((nsl - angle1) * 60) - min1) * 60, 2)
    second2 = round((((ewl - angle2) * 60) - min2) * 60, 2)

    print("北纬：{}度{}分{}秒".format(angle1, min1, second1))
    print("东经：{}度{}分{}秒".format(angle2, min2, second2))


def find_address_from_GPS(GPS):
    """
    使用Geocoding API把经纬度坐标转换为结构化地址。
    :param GPS:
    :return:
    """

    if not GPS['GPS_information']:
        print('No gps info')
        return None
    
    lat = GPS['GPS_information'].get('GPSLatitude')
    lng = GPS['GPS_information'].get('GPSLongitude')
    
    if lat is None or lng is None:
        print("no  lat or lng")
        return None
    
    # # 打印十进制度数的经纬度
    # print("\n照片的经纬度(十进制度数:")
    # print("纬度：{:.6f}".format(lat))
    # print("经度：{:.6f}".format(lng))
    
    # # 打印度分秒
    # print("\n照片的经纬度(度分秒):")
    # Position(lat, lng)

    location = "%.6f,%.6f"%(lng,lat)
    # print(location)
    # print(gLocToAddr)
    if location in gLocToAddr:
        addr = gLocToAddr[location]
        # print(addr)
        return addr
    addr = get_address_by_gaode(location)
    if addr is not None:
        gLocToAddr[location] = addr
    return addr


def sort_to(orig, dest):
    """
    Description : 递归重命名一个目录下所有的照片名字，优先读取照片拍摄时间，如果读取不到则读取图片最后修改时间，
    命名格式为:IMG_20170616_221206.JPG,...
    Modify      : 2021.04.12
    Input       : IN directory：待整理目录
    Return      :
    Caution     :
    """

    orig_path = Path(orig)
    dest_path = Path(dest)
    print("Path=", orig_path)
    # dirname = os.path.dirname(p)
    # print("dirname=", dirname)
    orig_parent = os.path.basename(orig_path)
    print("base_name=", orig_parent)

    for file in Path(orig).iterdir():
        if is_photo(file):
            GPS = {}
            target_file = None
            with open(file, "rb") as f:
                image_date = None
                tags = exifread.process_file(f)
                try:
                    for tag, value in tags.items():
                        # 纬度参考
                        if tag == 'GPS GPSLatitudeRef':
                            GPS['GPSLatitudeRef'] = str(value)
                        # 经度参考
                        elif tag == 'GPS GPSLongitudeRef':
                            GPS['GPSLongitudeRef'] = str(value)
                        # 海拔参考
                        elif tag == 'GPS GPSAltitudeRef':
                            GPS['GPSAltitudeRef'] = str(value)
                        elif tag == 'GPS GPSLatitude':
                            gps_latitude = value.values
                            deg, min, sec = [str(x) for x in gps_latitude]
                            GPS['GPSLatitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
                        elif tag == 'GPS GPSLongitude':
                            gps_longitude = value.values
                            deg, min, sec = [str(x) for x in gps_longitude]
                            GPS['GPSLongitude'] = latitude_and_longitude_convert_to_decimal_system(deg, min, sec)
                        elif tag == 'GPS GPSAltitude':
                            GPS['GPSAltitude'] = str(value)
                        elif 'Date' in tag:
                            date = str(value)
                    GPS_info = {'GPS_information': GPS, 'date_information': date}
                    address = find_address_from_GPS(GPS=GPS_info)
                    if address is None:
                        continue

                    dest_dir = address['province'] + '_' + address['city'] + '_'+ address['district']
                    print(dest_dir)
                    full_path = dest_path/dest_dir
                    if not os.path.exists(full_path):
                        Path(full_path).mkdir(exist_ok=True)
                    full_path = full_path/'photos'
                    if not os.path.exists(full_path):
                        Path(full_path).mkdir(exist_ok=True)
                    full_path = full_path/orig_parent
                    if not os.path.exists(full_path):
                        Path(full_path).mkdir(exist_ok=True)

                    file_name, file_extension = os.path.splitext(file.name)
                    new_file_name = file_name + '_' + orig_parent  + file_extension
                    target_file = Path(full_path/new_file_name)

                except Exception as e:
                    print(file, " Read Photo ERROR e=%s", str(e) + traceback.format_exc())

            if  target_file is not None:
                print("Move ", file, " to ", target_file)
                shutil.move(file, target_file)
        elif is_video_file(file):
            # print(file, " is video")
            continue
        else:
            print(file, " is unknown format")


def show_usage():
    print('sort.py in target')


if '__main__' == __name__:
    if (len(sys.argv) <= 1) or (sys.argv[1] == '-h'):
        show_usage()
        exit(0)

    pic_dir = sys.argv[1]
    print(pic_dir)
    if not os.path.isdir(pic_dir):
        print("pic_dir:", pic_dir, " is not dir")
        exit(-1)

    target_dir = sys.argv[2]
    if not os.path.isdir(target_dir):
        print("target_dir:", target_dir, " is not dir")
        exit(-1)


    # 从文件中读取字典
    if os.path.isfile("loc_to_addr.json"):
        with open("loc_to_addr.json", "r") as f:
            gLocToAddr = json.load(f)

    print("00000000000000 -- len(gLocToAddr)=", len(gLocToAddr))
    sort_to(pic_dir, target_dir)
    print("11111111111111 -- len(gLocToAddr)=", len(gLocToAddr))
    # 将字典保存到文件
    with open("loc_to_addr.json", "w") as f:
        json.dump(gLocToAddr, f)


